import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.HyperlinkEvent;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class DeepSeekChatApp extends JFrame {

    private final JTextPane chatPane;
    private final JTextField inputField;
    private final JButton sendButton;
    private final List<Message> conversationHistory = new ArrayList<>();
    private final Color bgColor = new Color(255, 255, 255);
    private final Color headerColor = new Color(50, 100, 200);
    private final Color userBubble = new Color(225, 245, 254);
    private final Color aiBubble = new Color(230, 255, 230);
    private final Color textColor = new Color(50, 50, 50);
    private final Font messageFont = new Font("微软雅黑", Font.PLAIN, 14);
    private final Font headerFont = new Font("微软雅黑", Font.BOLD, 20);

    public DeepSeekChatApp() {
        setTitle("DeepSeek AI 助手");
        setSize(850, 650);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout(10, 10));
        getContentPane().setBackground(bgColor);

        JPanel headerPanel = new JPanel();
        headerPanel.setBackground(headerColor);
        headerPanel.setBorder(new EmptyBorder(15, 25, 15, 25));
        headerPanel.setLayout(new BorderLayout());

        JLabel titleLabel = new JLabel("DeepSeek AI 聊天助手");
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setFont(headerFont);
        headerPanel.add(titleLabel, BorderLayout.WEST);

        add(headerPanel, BorderLayout.NORTH);

        chatPane = new JTextPane();
        chatPane.setEditable(false);
        chatPane.setFont(messageFont);
        chatPane.setBackground(bgColor);
        chatPane.setContentType("text/html");
        chatPane.setText("<html><body style='padding: 15px; font-family: 微软雅黑; font-size: 14pt; color: #333;'></body></html>");

        // 添加超链接监听实现点击复制
        chatPane.addHyperlinkListener(e -> {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                String desc = e.getDescription();
                if (desc.startsWith("copy:")) {
                    int index = Integer.parseInt(desc.substring(5));
                    if (index >= 0 && index < conversationHistory.size()) {
                        String text = conversationHistory.get(index).content;
                        copyToClipboard(text);
                        JOptionPane.showMessageDialog(this, "已复制内容！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        });

        JScrollPane scrollPane = new JScrollPane(chatPane);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        scrollPane.setBackground(bgColor);
        add(scrollPane, BorderLayout.CENTER);

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout(15, 15));
        inputPanel.setBorder(new EmptyBorder(15, 20, 20, 20));
        inputPanel.setBackground(bgColor);

        inputField = new JTextField();
        inputField.setFont(messageFont);
        inputField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(180, 180, 180)),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)
        ));
        inputField.setBackground(new Color(250, 250, 250));
        inputField.setForeground(textColor);
        inputField.addActionListener(e -> sendMessage());

        sendButton = new JButton("发送");
        sendButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        sendButton.setBackground(new Color(130, 130, 220));
        sendButton.setForeground(Color.gray);
        sendButton.setFocusPainted(false);
        sendButton.setBorder(BorderFactory.createEmptyBorder(12, 35, 12, 35));
        sendButton.addActionListener(e -> sendMessage());

        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        add(inputPanel, BorderLayout.SOUTH);

        appendToChat("DeepSeek AI", "您好！我是DeepSeek AI助手，有什么可以帮您的吗？", false);
    }

    private void sendMessage() {
        String userInput = inputField.getText().trim();
        if (userInput.isEmpty()) return;

        conversationHistory.add(new Message("user", userInput));
        appendToChat("您", userInput, true);

        inputField.setText("");
        sendButton.setEnabled(false);

        new Thread(() -> {
            try {
                StringBuilder requestBody = new StringBuilder("{\"messages\": [");
                for (Message msg : conversationHistory) {
                    requestBody.append(String.format(
                            "{\"role\":\"%s\",\"content\":\"%s\"},",
                            msg.role, escapeJson(msg.content)
                    ));
                }
                requestBody.deleteCharAt(requestBody.length() - 1);
                requestBody.append("]}");

                URL url = new URL("http://localhost:3000/api/chat-stream");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Accept", "text/event-stream");
                connection.setDoOutput(true);
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(60000);

                try (OutputStream os = connection.getOutputStream()) {
                    os.write(requestBody.toString().getBytes());
                    os.flush();
                }

                if (connection.getResponseCode() == 200) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                        StringBuilder aiResponse = new StringBuilder();
                        String line;
                        boolean isFirstChunk = true;

                        while ((line = reader.readLine()) != null) {
                            if (line.startsWith("data: ")) {
                                String jsonData = line.substring(6).trim();
                                if (jsonData.equals("[DONE]")) break;

                                if (jsonData.contains("\"content\":\"")) {
                                    String content = jsonData.split("\"content\":\"")[1]
                                            .split("\"")[0]
                                            .replace("\\n", "<br>")
                                            .replace("\\\"", "\"");

                                    if (!content.isEmpty()) {
                                        if (isFirstChunk) {
                                            conversationHistory.add(new Message("assistant", ""));
                                            isFirstChunk = false;
                                        }
                                        aiResponse.append(content);
                                        conversationHistory.get(conversationHistory.size() - 1).content += content;

                                        SwingUtilities.invokeLater(() -> {
                                            renderConversation();
                                            scrollToBottom();
                                        });
                                    }
                                }
                            }
                        }
                    }
                } else {
                    showError("API请求失败: HTTP " + connection.getResponseCode());
                }
            } catch (IOException ex) {
                showError("连接错误: " + ex.getMessage());
            } finally {
                SwingUtilities.invokeLater(() -> sendButton.setEnabled(true));
            }
        }).start();
    }

    private void renderConversation() {
        StringBuilder html = new StringBuilder(
                "<html><body style='font-family: 微软雅黑; font-size: 14pt; color: #333; padding: 15px;'>");

        for (int i = 0; i < conversationHistory.size(); i++) {
            Message msg = conversationHistory.get(i);
            boolean isUser = "user".equals(msg.role);
            String sender = isUser ? "\uD83D\uDC64" : "\uD83E\uDD16";
            Color bubbleColor = isUser ? userBubble : aiBubble;
            String safeContent = msg.content.replace("\n", "<br>");

            html.append("<div style='margin-bottom: 20px; max-width: 80%; clear: both;'>")
                    .append("<div style='font-weight: bold; color: ").append(isUser ? "#2c6ca6" : "#2c8c2c")
                    .append("; margin-bottom: 5px;'>").append(sender).append("</div>")
                    .append("<div style='background: rgb(").append(bubbleColor.getRed()).append(",")
                    .append(bubbleColor.getGreen()).append(",").append(bubbleColor.getBlue())
                    .append("); border-radius: 12px; padding: 12px 18px; display: inline-block; float: ")
                    .append(isUser ? "right" : "left")
                    .append("; text-align: left; box-shadow: 0 2px 4px rgba(0,0,0,0.1); position: relative;'>")
                    .append(safeContent)
                    .append("<br><a href='copy:").append(i)
                    .append("' style='font-size: 10pt; color: #888; float: right; text-decoration: none;'>📋 复制</a>")
                    .append("</div></div><div style='clear: both;'></div>");
        }

        html.append("</body></html>");
        chatPane.setText(html.toString());
    }

    private void scrollToBottom() {
        SwingUtilities.invokeLater(() -> {
            JScrollBar vertical = ((JScrollPane) chatPane.getParent().getParent()).getVerticalScrollBar();
            vertical.setValue(vertical.getMaximum());
        });
    }

    private void appendToChat(String sender, String message, boolean isUser) {
        renderConversation();
        scrollToBottom();
    }

    private void showError(String message) {
        SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE));
    }

    private String escapeJson(String input) {
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    private void copyToClipboard(String text) {
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            DeepSeekChatApp app = new DeepSeekChatApp();
            app.setVisible(true);

            // 👉 程序启动时自动将光标聚焦到输入框
            app.inputField.requestFocusInWindow();
        });
    }

    static class Message {
        String role;
        String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
    }
}

